﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Net;
using System.Text;
using System.Web.Services;
using DataAccessObject;
using EntityObject;
using SharedLibraries;
using SharedLibraries.Constants;
using ThangNM_LIB.DB;
using ThangNM_LIB.EO;
using ThangNM_LIB.FUNC;

namespace ThangNM.Admin
{
    public partial class WS_AJAX : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

            MsgUC1.setClearMsg();
            if (!IsPostBack)
            {
                if ((new ShareDAO.UserDAO()).SelectBy_sPermission(Session["secret"], Convert.ToString(Request.Url.AbsolutePath), ConstEx.funcButtonToolBar.MAIN) == false)
                {
                    lblsContent.Visible = false;
                    Commons.setAccessDenied(Page, MsgUC1);
                    return;
                }
            }
            if (Request.Cookies["preview"] != null)
                lblsContent.Text = Security.Login.Decrypt(Request.Cookies["preview"].Value, System.Configuration.ConfigurationManager.AppSettings["FACEBOOK"]);
            else
                Response.Redirect("~/");
        }

        #region "WebMethod"
        [WebMethod]
        public static string RegNewsLetter(string sEmail)
        {
            return Commons.RegNewsLetter(sEmail);
        }

        [WebMethod]
        public static string UpdateQuantityDownload(string sEmail)
        {
            string[] key = sEmail.Split('.');
            if (key.Length > 3)
            {
                (new FileDAO()).Update_iQuantityDownload(Convert.ToInt32(key[key.Length - 2]));
            }
            //return HttpUtility.ParseQueryString(sEmail)["f"];
            return sEmail;
        }

        [WebMethod]
        public static List<object> GetChartData(Int16 iType)
        {
            try
            {
                //System.Threading.Thread.Sleep(3000);
                TempEO objTemp = (new TempDAO()).SelectItem(Temp_PK_iTempID_C.CHART);
                DataSet dsTemp = new DataSet();
                dsTemp = (DataSet)JsonEx.Json2Object(objTemp.sContent, dsTemp.GetType());

                //DataSet dsTemp = CustomerCache.get_dsChart().Copy();
                int DATA_FILE_SIZE_MAX = 0;
                int LOG_FILE_SIZE_MAX = 0;
                int DATA_FILE_SIZE_USED = 0;
                int LOG_FILE_SIZE_USED = 0;
                DataTable dt = new DataTable();
                List<object> chartData = new List<object>();
                chartData.Add(new object[] { "NAME", "TOTAL" });


                switch (iType)
                {
                    case 0: // 0. tblCategory
                        foreach (DataRow dr in dsTemp.Tables[iType].Rows)
                        {
                            chartData.Add(new object[] { dr["NAME"].ToString(), dr["TOTAL"] });
                        }
                        return chartData;
                    case 1: // 1. tblMedia
                        foreach (DataRow dr in dsTemp.Tables[iType].Rows)
                        {
                            chartData.Add(new object[] { GetTextConstants.Media_iType_GTC(Convert.ToInt16(dr["NAME"])), dr["TOTAL"] });
                        }
                        return chartData;
                    case 2: // 2. tblAccount
                        foreach (DataRow dr in dsTemp.Tables[iType].Rows)
                        {
                            chartData.Add(new object[] { GetTextConstants.Account_iPermission_GTC(Convert.ToInt16(dr["NAME"])), dr["TOTAL"] });
                        }
                        return chartData;
                    case 3: // 4.tblFile
                        foreach (DataRow dr in dsTemp.Tables[iType].Rows)
                        {
                            chartData.Add(new object[] { GetTextConstants.File_iType_GTC(Convert.ToInt16(dr["NAME"])), dr["TOTAL"] });
                        }
                        return chartData;
                    case 4: // 8. Topic by Month - Year
                        chartData.Clear();
                        chartData.Add(new object[] { "Tháng - Năm", "Giải trí", "Bài viết", "Tài khoản", "Hỏi đáp" });
                        foreach (DataRow dr in dsTemp.Tables[iType].Rows)
                        {
                            chartData.Add(new object[] { dr["MONTH_YEAR"] = DateTime.ParseExact(Convert.ToString(dr["MONTH_YEAR"]), "yyyyMM", System.Globalization.CultureInfo.InvariantCulture).ToString("MM/yyyy"), dr["MEDIA"], dr["TOPIC"], dr["ACCOUNT"], dr["QUESTION_ANSWER"] });
                        }
                        return chartData;
                    case 5: // 9.QuestionAnswer
                        foreach (DataRow dr in dsTemp.Tables[iType].Rows)
                        {
                            chartData.Add(new object[] { GetTextConstants.QuestionAnswer_iType_GTC(Convert.ToInt16(dr["NAME"])), dr["TOTAL"] });
                        }
                        return chartData;
                    case 6: // 10.Topic
                        foreach (DataRow dr in dsTemp.Tables[iType].Rows)
                        {
                            chartData.Add(new object[] { GetTextConstants.Topic_iStatus_GTC(Convert.ToInt16(dr["NAME"])), dr["TOTAL"] });
                        }
                        return chartData;
                    case 7: // 11. Topic by Month - Year
                        chartData.Clear();
                        chartData.Add(new object[] { "Tháng - Năm", "Chơi game", "Tải game", "Xem phim tv online", "Nghe nhạc radio", "Sách - Truyện", "Hình ảnh động", "Độc và lạ" });
                        foreach (DataRow dr in dsTemp.Tables[iType].Rows)
                        {
                            chartData.Add(new object[] { dr["MONTH_YEAR"] = DateTime.ParseExact(Convert.ToString(dr["MONTH_YEAR"]), "yyyyMM", System.Globalization.CultureInfo.InvariantCulture).ToString("MM/yyyy"), dr["CHOI_GAME"], dr["TAI_GAME"], dr["XEM_PHIM_TV_ONLINE"], dr["NGHE_NHAC_RADIO"], dr["SACH_TRUYEN"], dr["HINH_ANH_DONG"], dr["DOC_VA_LA"] });
                        }
                        return chartData;
                    case 8: // 12. Database
                        chartData.Clear();
                        chartData.Add(new object[] { "name", "rows", "reserved (KB)", "data (KB)", "index_size (KB)", "unused (KB)" });
                        foreach (DataRow dr in dsTemp.Tables[iType].Rows)
                        {
                            chartData.Add(new object[] { dr["name"], StringEx.RemoveKB(dr["rows"]), StringEx.RemoveKB(dr["reserved"]), StringEx.RemoveKB(dr["data"]), StringEx.RemoveKB(dr["index_size"]), StringEx.RemoveKB(dr["unused"]) });
                        }
                        return chartData;
                    case 9: // 6. DataFile
                        dt = (new DB_SQL_EXT()).getDatabaseSizeCurrent(System.Configuration.ConfigurationManager.AppSettings["DATABASE_NAME"]);
                        if (DataTableEx.DataTable_OK(dt))
                        {
                            DATA_FILE_SIZE_USED = Convert.ToInt32(dt.Rows[0]["Database_DataFile_MB"]);
                            LOG_FILE_SIZE_USED = Convert.ToInt32(dt.Rows[0]["Database_LogFile_MB"]);
                        }
                        DATA_FILE_SIZE_MAX = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["DATA_FILE_SIZE_MAX"]);
                        LOG_FILE_SIZE_MAX = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["LOG_FILE_SIZE_MAX"]);
                        chartData.Add(new object[] { "Used spase", DATA_FILE_SIZE_USED });
                        chartData.Add(new object[] { "Free spase", DATA_FILE_SIZE_MAX - DATA_FILE_SIZE_USED });
                        return chartData;
                    case 10: // 7. LogFile
                        dt = (new DB_SQL_EXT()).getDatabaseSizeCurrent(System.Configuration.ConfigurationManager.AppSettings["DATABASE_NAME"]);
                        if (DataTableEx.DataTable_OK(dt))
                        {
                            DATA_FILE_SIZE_USED = Convert.ToInt32(dt.Rows[0]["Database_DataFile_MB"]);
                            LOG_FILE_SIZE_USED = Convert.ToInt32(dt.Rows[0]["Database_LogFile_MB"]);
                        }
                        DATA_FILE_SIZE_MAX = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["DATA_FILE_SIZE_MAX"]);
                        LOG_FILE_SIZE_MAX = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["LOG_FILE_SIZE_MAX"]);
                        chartData.Add(new object[] { "Used spase", LOG_FILE_SIZE_USED });
                        chartData.Add(new object[] { "Free spase", LOG_FILE_SIZE_MAX - LOG_FILE_SIZE_USED });
                        return chartData;
                    case 11: // 5. Error
                        foreach (DataRow dr in dsTemp.Tables[iType].Rows)
                        {
                            chartData.Add(new object[] { dr["NAME"].ToString(), dr["TOTAL"] });
                        }
                        return chartData;
                    case 12: // 3. Tag
                        foreach (DataRow dr in dsTemp.Tables[iType].Rows)
                        {
                            chartData.Add(new object[] { dr["NAME"].ToString(), dr["TOTAL"] });
                        }
                        return chartData;
                }
                return null;
            }
            catch (Exception ex)
            {
                (new Logs()).WriteLog_To_DB(new LogEO(ex.ToString(), ConstEx.Log_iType.EXCEPTION), false);
                System.Web.HttpContext.Current.Response.Write("<SCRIPT>alert('Lỗi không lấy được dữ liệu." + ex.ToString() + "')</SCRIPT>");
                return null;
            }
        }

        [WebMethod]
        public static Boolean Comment_Visit_Like(String token, String value)
        {
            try
            {
                SEO_EXEO _SEO_EXEO = new SEO_EXEO();
                token = System.Web.HttpUtility.UrlDecode(token);
                token = Security.Login.Decrypt(token, System.Configuration.ConfigurationManager.AppSettings["FACEBOOK"]);
                var objTemp = JsonEx.Json2Object(token, _SEO_EXEO.GetType());
                if (objTemp != null)
                    _SEO_EXEO = (SEO_EXEO)objTemp;
                if (_SEO_EXEO.tTimeout >= DateTime.Now)
                {
                    //DisqusEO _DisqusEO = new DisqusEO();
                    //String downloadString = "";
                    //try
                    //{
                    //    if (String.IsNullOrEmpty(value))
                    //    {
                    //        using (var client = new WebClient())
                    //        //using (var stream = client.OpenRead("http://nguyenmanhthang.disqus.com/count-data.js?1="+_SEO_EXEO.PK_iTable +_SEO_EXEO.PK_iSEO))
                    //        using (var stream = client.OpenRead("http://me.zing.vn"))
                    //        using (var textReader = new StreamReader(stream, Encoding.UTF8, true))
                    //        {
                    //            downloadString = System.Web.HttpUtility.HtmlDecode(textReader.ReadToEnd());
                    //            var disqus = JsonEx.Json2Object(downloadString, _DisqusEO.GetType());
                    //            if (disqus != null)
                    //                _DisqusEO = (DisqusEO)disqus;
                    //            if (_DisqusEO != null && _DisqusEO.comments != _SEO_EXEO.iComment_iLike)
                    //            {
                    //                _SEO_EXEO.iComment_iVisit_iLike = 4;
                    //                _SEO_EXEO.iComment_iLike = _DisqusEO.comments;
                    //            }
                    //        }
                    //    }
                    //    else if (_SEO_EXEO.iComment_iVisit_iLike == 3)
                    //    {
                    //        _SEO_EXEO.iComment_iVisit_iLike = 3;
                    //        _SEO_EXEO.iComment_iLike = Convert.ToInt32(value);
                    //    }
                    //}
                    //catch
                    //{
                    //    return false;
                    //}
                    if (_SEO_EXEO.iComment_iVisit_iLike > 0)
                    {
                        return (new SEODAO()).Update_iComment_iVisit_iLike(_SEO_EXEO);
                    }
                    return false;
                }
                else
                    return false;
            }
            catch
            {
                return false;
            }
        }


        protected static string ReCaptcha_Secret = "6LfLcQoTAAAAAOA9wd66nrlyoXbY9hXjllyEUlsR";
        [WebMethod]
        public static string VerifyCaptcha(string response)
        {
            string url = "https://www.google.com/recaptcha/api/siteverify?secret=" + ReCaptcha_Secret + "&response=" + response;
            return (new WebClient()).DownloadString(url);
        }
        #endregion
    }
}